var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require("express-session");

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// 引入 routes 文件夹下的 admin 模块
const admin = require("./routes/admin");
var app = express();

// 配置 session 中间件
app.use(session({
    secret: "Duba manage",
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 1000 * 60 * 60 * 20 }
}));

app.set('views', path.join(__dirname, 'views')); // 模板引擎设置
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/admin", admin); // 加载 admin 模块
// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || 500);
    res.render('error'); // 渲染错误页面
});

module.exports = app;
app.listen(3006, function(){ // 监听端口
    console.log('http://localhost:3006/admin/login');
});